<template>
  <base-modal :title="title" :width="mode === 'projectType' ? '500px' : '674px'" @cancel="cancel" :show.sync="isShow" :mask-closeable="false">
    <div v-if="!clickTaskType" class="add-task-type">
      <el-row type="flex" justify="space-between">
        <el-card class="choose-type-box" :class="getCardActive(item.type) && 'active'" :style="{ 'background-image': 'url(' + item.bgImg + ')' }" v-for="item in taskTemplateList" :key="item.type" shadow="hover" @click.native="chooseTypeTemplate(item.type)" @mouseenter.native="enterCard(item.type)" @mouseleave.native="hoverTaskType = ''">
          <div class="choose-type-box-content">
            <h2>{{ item.title }}</h2>
            <p class="task-type-desc">{{ item.desc }}</p>
          </div>
        </el-card>
      </el-row>
    </div>
    <el-form label-position="top" v-else :model="form" :rules="rules" ref="form" class="add-task-form" onsubmit="return false;">
      <el-form-item v-if="clickTaskType === 'exist'" :label="isTaskType ? $t('common.task.taskType') : $t('common.projectManage.projectTypeName')">
        <el-select v-model="form.templetId" :placeholder="$t('common.placeholder.selectSomething', { 0: isTaskType ? $t('common.task.taskType') : $t('common.projectManage.projectTypeName') })" class="w-360">
          <el-option v-for="item in taskTypeList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('projectManage.projectType.new.label1')" prop="typeName">
        <el-input class="w-360" maxlength="20" v-model="form.typeName" :placeholder="$t('task.setting.taskTypeSetting.manage.tip1')"></el-input>
        <base-select-language v-if="isTaskType" :field="{}" :defaultValueLanguage="form.nameLanguageMap" :defaultValue="form.typeName" @save="save"></base-select-language>
      </el-form-item>
      <el-form-item>
        <ul class="statecolor">
          <li v-for="color in taskTypeColor" :key="color" @click="form.color = color" :style="{ background: color }">
            <i class="el-icon-check" v-if="color === form.color"></i>
          </li>
        </ul>
      </el-form-item>
    </el-form>

    <div v-if="clickTaskType" slot="footer">
      <el-button @click="cancel">{{ $t('common.base.cancel') }}</el-button>
      <el-button :loading="pedding" type="primary" @click="createTaskType">{{ $t('common.base.makeSure') }}</el-button>
    </div>

    <!-- 选择行业模板弹窗 -->
    <choose-trade-dialog :visiable.sync="isShowChooseTradeDialog" @select="selectTemplate" />
  </base-modal>
</template>

<script>
/** api */
import * as SettingApi from '@src/api/SettingApi.ts';
// assets
import { getOssUrl } from '@src/util/assets';
const taskTemplateBlank = getOssUrl('/setting/task-template-blank.png');
const taskTemplateCopy = getOssUrl('/setting/task-template-copy.png');
const taskTemplateTrade = getOssUrl('/setting/task-template-trade.png');

// components
import ChooseTradeDialog from './ChooseTradeDialog.vue';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import i18n from '@src/locales';
const TASK_TYPE_COLOR = ['rgb(115,127,124)', 'rgb(38,111,255)', 'rgb(82,85,255)', 'rgb(133,82,255)', 'rgb(188,82,255)', 'rgb(255,82,212)', 'rgb(255,149,38)', 'rgb(110,207,64)', 'rgb(0,184,213)', 'rgb(11,161,148)'];

export default {
  name: 'add-task-type-dialog',
  props: {
    visiable: {
      type: Boolean,
      default: false,
    },
    taskTypeList: {
      type: Array,
      default: () => [],
    },
    mode: {
      type: String,
      default: 'taskType',
    },
  },
  data() {
    return {
      hoverTaskType: '',
      clickTaskType: '',

      form: {
        typeName: '',
        taskTypeId: '',
        templetId: '',
        color: 'rgb(115,127,124)',
        nameLanguageMap: {},
      },

      pedding: false,
      isShow: false,
      isShowChooseTradeDialog: false,
    };
  },
  computed: {
    taskTypeColor() {
      return TASK_TYPE_COLOR;
    },
    title() {
      return (this.clickTaskType && this.clickTaskType !== 'blank') ? this.taskTemplateList.find(item => item.type === this.clickTaskType).title : this.isTaskType ? i18n.t('task.setting.taskTypeSetting.manage.createTaskType') : i18n.t('projectManage.projectType.new.title');
    },
    // projectManage.projectType.new.title
    taskTemplateList() {
      const desc = this.mode === 'projectType' ? i18n.t('task.setting.taskTypeSetting.manage.desc4') : i18n.t('task.setting.taskTypeSetting.manage.desc1')
      return [
        {
          type: 'blank',
          title: i18n.t('common.base.createFromBlankTemplate'),
          desc,
          bgImg: taskTemplateBlank,
        },
        {
          type: 'exist',
          title: i18n.t('task.setting.taskTypeSetting.manage.title7'),
          desc: i18n.t('task.setting.taskTypeSetting.manage.desc2'),
          bgImg: taskTemplateCopy,
        },
        ...(this.isTaskType
          ? [
              {
                type: 'template',
                title: i18n.t('task.setting.taskTypeSetting.manage.title8'),
                desc: i18n.t('task.setting.taskTypeSetting.manage.desc3'),
                bgImg: taskTemplateTrade,
              },
            ]
          : []),
      ];
    },
    isTaskType() {
      return this.mode === 'taskType';
    },
    isProjectType() {
      return this.mode === 'projectType';
    },
    rules() {
      let validateTypeName = (rule, value, callback) => {
        if (value === '') return callback(new Error(this.isTaskType ? i18n.t('task.setting.taskTypeSetting.flow.placeholder1') : i18n.t('common.placeholder.selectSomething', { 0: 18n.t('common.projectManage.projectTypeName') })));
        if (value.length > 100) callback(new Error(i18n.t('common.validate.nameLimit', { limit: '100' })));
        // if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) return callback(new Error(i18n.t('task.setting.taskTypeSetting.manage.tip3')));

        callback();
      };
      return {
        taskType: [{ required: true, message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('common.task.taskType')}), trigger: 'blur' }],
        templetId: [{ required: true, message: i18n.t('common.placeholder.selectSomething', { 0: this.isTaskType ? i18n.t('common.task.taskType') : i18n.t('common.projectManage.projectTypeName') }), trigger: 'blur' }],
        typeName: [
          { required: true, message: this.isTaskType ? i18n.t('task.setting.taskTypeSetting.flow.placeholder1') : i18n.t('common.placeholder.inputSomething', { data1: i18n.t('projectManage.projectType.new.label1') }), trigger: 'blur' },
          { validator: validateTypeName, trigger: 'blur' },
        ],
      };
    },
  },
  watch: {
    visiable(newVal) {
      this.isShow = newVal;
    },
  },
  methods: {
    enterCard(type) {
      this.hoverTaskType = type;
    },
    getCardActive(type) {
      return this.hoverTaskType === type;
    },
    cancel() {
      let _this = this;
      this.$emit('update:visiable', false);
      setTimeout(() => {
        Object.assign(this.$data, this.$options.data());
        _this.$refs.form.resetFields();
      }, 100);
    },
    /** 选择行业模板 */
    selectTemplate({ taskTypeId, typeName }) {
      this.clickTaskType = 'template';
      this.form = {
        ...this.form,
        typeName,
        taskTypeId,
      };
    },
    /** 选择新建类型 */
    chooseTypeTemplate(type) {
      if (type === 'template') {
        return (this.isShowChooseTradeDialog = true);
      }

      this.clickTaskType = type;
    },
    /**
     * 创建工单
     */
    createTaskType() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let fromId = window.frameElement?.getAttribute('id');
          if (this.isProjectType) {
            return this.$emit('submit', this.form);
          }
          // 从行业模板创建
          if (this.clickTaskType === 'template') {
            this.pedding = true;
            let params = {
              taskTypeName: this.form.typeName,
              color: this.form.color,
              taskTypeId: this.form.taskTypeId,
            };
            SettingApi.importTaskType(params)
              .then(res => {
                if (res.status == 0) {
                  // this.$platform.openTab({
                  //   id: 'task_form_setting',
                  //   title: '工单类型设置',
                  //   url: `/setting/task/taskFormSet?taskTypeId=${ res.data }&new=true`,
                  //   reload: true,
                  //   fromId
                  // });
                  openAccurateTab({
                    type: PageRoutesTypeEnum.PageTaskFlowSetting,
                    titleKey: this.$t('task.setting.taskTypeSettings'),
                    params: `taskTypeId=${res.data}&new=true`,
                    reload: true,
                    fromId,
                  });
                } else {
                  this.$platform.notification({
                    title: res.message,
                    type: 'error',
                  });
                }
              })
              .catch(err => {
                console.error(err);
              })
              .finally(() => {
                this.pedding = false;
              });
            return;
          }

          // 从空白模板/现有工单类型创建
          this.pedding = true;
          SettingApi.createInitTaskType(this.form)
            .then(res => {
              if (res.status == 0) {
                // this.$platform.openTab({
                //   id: 'task_form_setting',
                //   title: '工单类型设置',
                //   url: `/setting/task/taskFormSet?taskTypeId=${ res.data }&new=true`,
                //   reload: true,
                //   fromId
                // });
                openAccurateTab({
                  type: PageRoutesTypeEnum.PageTaskFlowSetting,
                  titleKey: this.$t('task.setting.taskTypeSettings'),
                  params: `taskTypeId=${res.data}&new=true`,
                  reload: true,
                  fromId,
                });
                let id = window.frameElement.dataset.id;
                this.$platform.refreshTab(id);
              } else {
                this.$platform.alert(res.message);
              }
            })
            .catch(err => {
              console.error(err);
            })
            .finally(() => {
              this.pedding = false;
            });
        }
      });
    },

    save(form) {
      this.form.nameLanguageMap = form;
      this.form.typeName = form[i18n.locale];
    },
  },
  components: {
    [ChooseTradeDialog.name]: ChooseTradeDialog,
  },
};
</script>

<style lang="scss" scoped>
.add-task-type {
  max-height: 403px;
  padding: 40px 40px 20px 40px;
  overflow: hidden;
  .choose-type-box {
    cursor: pointer;
    position: relative;
    width: 183px;
    height: 244px;
    border-radius: 10px;

    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;

    &.active {
      .choose-type-box-content {
        transform: translateY(0);
        p {
          opacity: 1;
        }
      }
    }

    .choose-type-box-content {
      position: absolute;
      left: 16px;
      bottom: 17px;
      color: #ffffff;
      transform: translateY(22px);
      transition: all 0.5s ease;

      h2 {
        margin-bottom: 5px;
        font-size: 16px;
      }
      p {
        margin-bottom: 0;
        font-size: 12px;
        opacity: 0;
        transition: all 0.5s ease;
      }
    }
  }
}

.add-task-form {
  padding: 20px;
  ul.statecolor {
    padding: 0;
    line-height: 22px;
    li {
      list-style: none;
      display: inline-block;
      cursor: pointer;
      margin-right: 4px;
      width: 32px;
      height: 22px;
      vertical-align: middle;
      i {
        position: relative;
        font-weight: bold;
        left: 9px;
        color: #fff;
      }
    }
  }
}

.w-360 {
  width: 360px;
}
</style>
